package com.nhjf.common.util;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class HttpClientUtil {
	private static String createParam(Map<String, String> parameters,
			String encoding) {
		if (parameters != null) {
			StringBuffer params = new StringBuffer();

			for (Iterator<Entry<String, String>> iter = parameters.entrySet()
					.iterator(); iter.hasNext(); params.append("&")) {
				java.util.Map.Entry<String, String> element = (java.util.Map.Entry<String, String>) iter
						.next();
				params.append(element.getKey().toString());
				params.append("=");
				try {
					params.append(URLEncoder.encode(element.getValue()
							.toString(), encoding));
				} catch (UnsupportedEncodingException e) {
				}
			}

			if (params.length() > 0) {
				params = params.deleteCharAt(params.length() - 1);
			}
			return params.toString();
		} else {
			return "";
		}

	}

	public static String send(String url, Map<String, String> parameters,
			String encoding) {
		try {
			URL url1 = new URL(url);

			HttpURLConnection connection = (HttpURLConnection) url1
					.openConnection();
			// 设置允许output
			connection.setDoOutput(true);
			// 设置为post方式
			connection.setRequestMethod("POST");
			connection.setRequestProperty("user-agent",
					"mozilla/4.7 [en] (win98; i)");
			String param = createParam(parameters, encoding);
			// post信息
			OutputStream os = connection.getOutputStream();
			os.write(param.getBytes());
			os.close();
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), encoding));
			connection.connect();
			String line = null;
			StringBuffer buffer = new StringBuffer();
			while ((line = reader.readLine()) != null) {
				buffer.append(line+"\n");
			}
			reader.close();
			return buffer.toString();
		} catch (Exception e) {
			LogMessage.logwrite(HttpClientUtil.class, e.getMessage());
			return null;
		}
	}
}
